const express = require('express');
const Transaction = require('../models/Transaction');
const Room = require('../models/Room');
const User = require('../models/User');
const { auth } = require('../middleware/auth');

const router = express.Router();

// 创建交易记录
router.post('/:roomId', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const { from, to, amount, description, type = 'transfer' } = req.body;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    if (!from || !to || !amount || amount <= 0) {
      return res.status(400).json({ message: '参数不完整或金额无效' });
    }
    
    // 确保amount按照人民币规则保留两位小数
    const amountDecimal = Math.round(Number(amount) * 100) / 100;
    
    // 验证房间
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否在房间中
    const isMember = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!isMember) {
      return res.status(403).json({ message: '您不是房间成员' });
    }
    
    // 验证交易双方是否在房间中
    const fromMember = room.members.find(member => 
      member.user.toString() === from.toString()
    );
    const toMember = room.members.find(member => 
      member.user.toString() === to.toString()
    );
    
    if (!fromMember || !toMember) {
      return res.status(400).json({ message: '交易双方必须在房间中' });
    }
    
    // 创建交易记录
    const transaction = new Transaction({
      room: roomId,
      from,
      to,
      amount: amountDecimal,
      description,
      type,
      createdBy: userId
    });
    
    await transaction.save();
    
    // 更新房间游戏记录
    room.addGameRecord([{
      from,
      to,
      amount: amountDecimal,
      description
    }], amountDecimal);
    
    await room.save();
    
    // 更新用户统计
    const fromUser = await User.findById(from);
    const toUser = await User.findById(to);
    
    if (fromUser) {
      fromUser.totalLosses += amountDecimal;
      fromUser.totalEarnings -= amountDecimal;
      await fromUser.save();
    }
    
    if (toUser) {
      toUser.totalWins += amountDecimal;
      toUser.totalEarnings += amountDecimal;
      await toUser.save();
    }
    
    res.status(201).json({
      message: '交易记录创建成功',
      transaction: {
        id: transaction._id,
        room: transaction.room,
        from: transaction.from,
        to: transaction.to,
        amount: transaction.amount,
        description: transaction.description,
        type: transaction.type,
        createdAt: transaction.createdAt
      }
    });
  } catch (error) {
    console.error('创建交易记录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 批量创建交易记录
router.post('/:roomId/batch', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const { transactions } = req.body;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    if (!transactions || !Array.isArray(transactions) || transactions.length === 0) {
      return res.status(400).json({ message: '交易记录不能为空' });
    }
    
    // 验证房间
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否在房间中
    const isMember = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!isMember) {
      return res.status(403).json({ message: '您不是房间成员' });
    }
    
    const createdTransactions = [];
    const roomTransactions = [];
    let totalAmount = 0;
    
    // 创建所有交易记录
    for (const trans of transactions) {
      const { from, to, amount, description, type = 'transfer' } = trans;
      
      if (!from || !to || !amount || amount <= 0) {
        continue;
      }
      
      // 确保amount按照人民币规则保留两位小数
      const amountDecimal = Math.round(Number(amount) * 100) / 100;
      
      // 验证交易双方是否在房间中
      const fromMember = room.members.find(member => 
        member.user.toString() === from.toString()
      );
      const toMember = room.members.find(member => 
        member.user.toString() === to.toString()
      );
      
      if (!fromMember || !toMember) {
        continue;
      }
      
      const transaction = new Transaction({
        room: roomId,
        from,
        to,
        amount: amountDecimal,
        description,
        type,
        createdBy: userId
      });
      
      await transaction.save();
      createdTransactions.push(transaction);
      roomTransactions.push({
        from,
        to,
        amount: amountDecimal,
        description
      });
      totalAmount += amountDecimal;
    }
    
    // 更新房间游戏记录
    if (roomTransactions.length > 0) {
      room.addGameRecord(roomTransactions, totalAmount);
      await room.save();
    }
    
    // 更新用户统计
    const userUpdates = {};
    for (const trans of roomTransactions) {
      if (!userUpdates[trans.from]) {
        userUpdates[trans.from] = { losses: 0, earnings: 0 };
      }
      if (!userUpdates[trans.to]) {
        userUpdates[trans.to] = { losses: 0, earnings: 0 };
      }
      
      userUpdates[trans.from].losses += trans.amount;
      userUpdates[trans.from].earnings -= trans.amount;
      userUpdates[trans.to].earnings += trans.amount;
    }
    
    for (const [userId, updates] of Object.entries(userUpdates)) {
      const user = await User.findById(userId);
      if (user) {
        user.totalLosses += updates.losses;
        user.totalWins += updates.earnings;
        user.totalEarnings += updates.earnings;
        await user.save();
      }
    }
    
    res.status(201).json({
      message: '批量交易记录创建成功',
      transactions: createdTransactions.map(t => ({
        id: t._id,
        room: t.room,
        from: t.from,
        to: t.to,
        amount: t.amount,
        description: t.description,
        type: t.type,
        createdAt: t.createdAt
      })),
      totalAmount
    });
  } catch (error) {
    console.error('批量创建交易记录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取房间交易记录
router.get('/:roomId', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    // 验证房间
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否在房间中
    const isMember = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!isMember) {
      return res.status(403).json({ message: '您不是房间成员' });
    }
    
    // 构建查询条件
    const query = { room: roomId };
    
    // 分页查询
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const transactions = await Transaction.find(query)
      .populate('from', 'username nickname')
      .populate('to', 'username nickname')
      .populate('createdBy', 'username nickname')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    const total = await Transaction.countDocuments(query);
    
    res.json({
      transactions: transactions.map(t => ({
        id: t._id,
        room: t.room,
        from: t.from,
        to: t.to,
        amount: t.amount,
        description: t.description,
        type: t.type,
        status: t.status,
        createdBy: t.createdBy,
        createdAt: t.createdAt
      })),
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (error) {
    console.error('获取交易记录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户在房间中的统计
router.get('/:roomId/user-stats/:userId', auth, async (req, res) => {
  try {
    const { roomId, userId } = req.params;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    // 验证房间
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否在房间中
    const isMember = room.members.find(member => 
      member.user.toString() === userId.toString()  
    );
    
    if (!isMember) {
      return res.status(403).json({ message: '用户不是房间成员' });
    }
    
    // 获取用户统计
    const stats = await Transaction.getUserStats(userId, roomId);
    
    res.json({
      userId,
      roomId,
      stats
    });
  } catch (error) {
    console.error('获取用户统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取房间统计
router.get('/:roomId/room-stats', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    // 验证房间
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否在房间中
    const isMember = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!isMember) {
      return res.status(403).json({ message: '您不是房间成员' });
    }
    
    // 获取房间统计
    const stats = await Transaction.getRoomStats(roomId);
    
    res.json({
      roomId,
      stats,
      memberCount: room.members.length
    });
  } catch (error) {
    console.error('获取房间统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除交易记录（仅创建者可以删除）
router.delete('/:transactionId', auth, async (req, res) => {
  try {
    const { transactionId } = req.params;
    const userId = req.user.userId;
    
    const transaction = await Transaction.findById(transactionId);
    if (!transaction) {
      return res.status(404).json({ message: '交易记录不存在' });
    }
    
    // 检查是否是创建者
    if (transaction.createdBy.toString() !== userId.toString()) {
      return res.status(403).json({ message: '只有创建者可以删除交易记录' });
    }
    
    // 检查是否可以删除（比如时间限制）
    const timeDiff = Date.now() - transaction.createdAt.getTime();
    const maxDeleteTime = 5 * 60 * 1000; // 5分钟
    
    if (timeDiff > maxDeleteTime) {
      return res.status(400).json({ message: '交易记录创建超过5分钟，无法删除' });
    }
    
    await Transaction.findByIdAndDelete(transactionId);
    
    res.json({ message: '交易记录删除成功' });
  } catch (error) {
    console.error('删除交易记录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 